<template>
	<div>
		<el-upload
			action="qqq"
			:auto-upload="true"
			:before-upload="handleInitRequestParam"
			:data="uploadData"
			:http-request="upload"
			list-type="picture-card"
			:multiple="false"
			:on-preview="handlePictureCardPreview"
			:on-remove="handleRemove"
		>
			<i class="el-icon-plus"></i>
		</el-upload>
		<el-dialog v-show="dialogVisible">
			<img alt="" :src="dialogImageUrl" width="100%" />
		</el-dialog>
	</div>
</template>

<script>
import axios from "axios"; // 引入
export default {
	data() {
		return {
			dialogImageUrl: "",
			dialogVisible: false,
			uploadData: {
				requestId: "",
				total: 1,
				index: 0,
				fileName: "",
				fileType: "",
			},
			imageFile: null,
		};
	},
	props: {
		objName: { type: String, default: "order" },
		orgCode: { type: String, default: "00000" },
	},
	methods: {
		handleRemove(file, fileList) {
			console.log(file, fileList);
		},
		handlePictureCardPreview(file) {
			this.dialogImageUrl = file.url;
			this.dialogVisible = true;
		},
		handleInitRequestParam(file) {
			this.imageFile = file;
			this.uploadData.fileName = file.name;
		},
		async upload() {
			// eslint-disable-next-line no-debugger
			//debugger;
			//上传文件单片2MB
			var chunkSize = 1024 * 1024 * 2;
			// 总分片数量
			var chunks = Math.ceil(this.imageFile.size / chunkSize);
			this.uploadData.total = chunks;
			this.uploadData.requestId = this.getFilelastModified();
			// 分包上传文件
			for (let index = 0; index < chunks; index++) {
				this.uploadData.index = index;
				var tempFile = null;
				if (index === chunks - 1) {
					tempFile = this.imageFile.slice(index * chunkSize);
				} else {
					tempFile = this.imageFile.slice(
						index * chunkSize,
						(index + 1) * chunkSize
					);
				}

				// 封装请求参数
				var data = new FormData();
				data.append("data", tempFile);
				data.append("requestId", this.uploadData.requestId);
				data.append("total", this.uploadData.total);
				data.append("index", this.uploadData.index);
				data.append("fileName", this.uploadData.fileName);
				data.append("fileType", this.uploadData.fileType);
				data.append("objName", this.objName);
				data.append("orgCode", this.orgCode);

				var res = await axios.post(
					"http://localhost:5000/api/Upload",
					data
				);
				// eslint-disable-next-line no-debugger
				//debugger;
				if (res.data.code === 200) {
					if (index === chunks - 1) {
						// 最后一包上传成功获取图片地址
						console.log(res.data.data.url);
					}
					// 获取请求id
					this.uploadData.requestId = res.data.data.requestId;
				}
			}
		},
		getFilelastModified: function () {
			var dd = new Date();
			return (
				dd.getFullYear().toString() +
				dd.getMonth().toString() +
				dd.getDate().toString() +
				dd.getHours().toString() +
				dd.getMinutes().toString() +
				dd.getSeconds().toString() +
				dd.getMilliseconds().toString()
			);
		},
	},
};
</script>
